using SmartCommunity.Models;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace SmartCommunity.WebApi.Services.System
{
    /// <summary>
    /// 服务类：字典明细
    /// </summary>
    public class DictItemService : BaseService<DictItemEntity>
    {
        #region 构造函数
        protected readonly SCDBContext ctx;
        public DictItemService(SCDBContext ctx)
        {
            this.ctx = ctx;
        }
        #endregion

        #region 数据查询 
        /// <summary>
        /// 根据字典明细ID查询
        /// </summary>
        public async Task<DictItemDto> FindDictItemById(int dictItemId)
        {
            var entity = await FindById(dictItemId);
            return entity.Adapt<DictItemDto>();
        }

        /// <summary>
        /// 根据ID查询实体类
        /// </summary>
        private async Task<DictItemEntity> FindById(int id)
        {
            return await ctx.DictItems.SingleOrDefaultAsync(a => a.DictItemId == id)
                ?? throw new NotFoundException($"找不到指定的字典明细,Id:{id}");
        }
        #endregion

        #region 增 删 改
        /// <summary>
        /// 新增字典明细
        /// </summary>
        public async Task<DictItemDto> CreateDictItem(DictItemDto dto, LoginUser user)
        {
            // 新建对象
            var entity = new DictItemEntity();
            // 复制属性
            await CopyDtoToEntity(dto, entity, user, true);
            // 执行保存
            ctx.DictItems.Add(entity);
            await ctx.SaveChangesAsync();
            // 返回Dto
            return entity.Adapt<DictItemDto>();
        }

        /// <summary>
        /// 更新字典明细
        /// </summary>
        public async Task UpdateDictItem(DictItemDto dto, LoginUser user)
        {
            // 原始数据
            var entity = await FindById(dto.DictItemId);
            // 更新字段
            await CopyDtoToEntity(dto, entity, user, false);
            // 执行更新
            await ctx.SaveChangesAsync();
        }

        /// <summary>
        /// 复制dto属性到实体字段
        /// </summary>
        private async Task CopyDtoToEntity(DictItemDto dto, DictItemEntity entity, LoginUser user, bool isNew)
        {
            var dict = await ctx.Dicts.Include(a => a.DictItems).SingleOrDefaultAsync(a => a.DictId == dto.DictId)
                  ?? throw new MessageException("找不到字典类别:" + dto.DictId);

            // 检查数据重复
            if (dict.DictItems.Any(a => a.DictItemId != dto.DictItemId && (a.DictValue == dto.DictValue || a.DictLabel == dto.DictLabel || a.DictCode == dto.DictCode)))
            {
                throw new MessageException("当前已存在相同名称或编码的字典明细");
            }
            entity.DictId = dto.DictId;
            entity.DictCode = dto.DictCode;
            entity.DictValue = dto.DictValue;
            entity.DictLabel = dto.DictLabel;
            entity.SortNo = dto.SortNo ?? 0;
            entity.Remark = dto.Remark;
            entity.Disabled = dto.Disabled;

            if (isNew)
            {
                if (!dto.SortNo.HasValue && dict.DictItems.Count == 0)
                {
                    entity.SortNo = (short)(dict.DictItems.Max(a => a.SortNo) + 1);
                }

            }

            // 记录操作人
            if (isNew)
            {
                entity.CreatedBy = user.Username;
                entity.CreatedTime = DateTime.Now;
            }
            entity.UpdatedBy = user.Username;
            entity.UpdatedTime = DateTime.Now;
        }

        /// <summary>
        /// 根据ID删除字典明细
        /// </summary>
        public async Task DeleteByIds(IEnumerable<int> ids, LoginUser user)
        {
            var dictItems = await ctx.DictItems.Where(a => ids.Contains(a.DictItemId)).ToListAsync();
            if (dictItems.Count != ids.Count())
            {
                throw new MessageException("查询出的数据和传入的ID不匹配，请刷新后再试。");
            }
            // 判断是否能删除
            foreach (var entity in dictItems)
            {
                ctx.DictItems.Remove(entity);
            }
            // 提交事务
            await ctx.SaveChangesAsync();
        }
        #endregion
    }
}
